package com.crm.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.crm.entity.Askers;
import com.crm.entity.Netfollows;
import com.crm.entity.Student;
import com.crm.entity.User;
import com.crm.repository.AskersRepository;
import com.crm.repository.NetfollowsRepository;
import com.crm.repository.StudentRepositoy;
import com.crm.repository.UserRepository;
import com.crm.service.NetfollowsService;
import com.crm.util.FenyeUtil;
@Service
public class NetfollowsServiceImpl implements NetfollowsService {

	@Autowired
	private NetfollowsRepository netfollowsRepository;
	@Autowired
	private UserRepository userrepostory;
	@Autowired
	private StudentRepositoy studentrepostory;
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Override
	public FenyeUtil<Netfollows> FindAskerByPage(Netfollows netf, Integer page,String userId,String stuId) {
		User use = userrepostory.findById(userId).get();
		//判断是否是管理员
        int pd=0;
        for(int i=0;i<use.getRlist().size();i++) {
        	if(use.getRlist().get(i).getRoleExplain().equals("管理员")) {
        		pd+=10;
        	}
        	if(use.getRlist().get(i).getRoleExplain().equals("咨询师经理")) {
        		pd+=10;
        	}
        }
        if(pd>0) {
        	userId=null;
        }
       
		Pageable pages = PageRequest.of(page-1, 10);
		Page<Netfollows> netlist = netfollowsRepository.findAll(get(netf,userId,stuId),pages);
		FenyeUtil<Netfollows> fenye = new FenyeUtil<Netfollows>();
		fenye.setCode(0);
		fenye.setData(netlist.getContent());
		fenye.setCount((int)netlist.getTotalElements());
		return fenye;
	}

	private Specification<Netfollows> get(Netfollows netf,String userId,String stuId) {
		return new Specification<Netfollows>() {
			
			@Override
			public Predicate toPredicate(Root<Netfollows> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if(!StringUtils.isEmpty(netf.getStudentName())) {
					expressions.add(criteriaBuilder.like(root.get("studentName"),"%"+netf.getStudentName()+"%"));
				}
				if(!StringUtils.isEmpty(netf.getFollowType())) {
					expressions.add(criteriaBuilder.like(root.get("followType"), "%"+netf.getFollowType()+"%"));
				}
				if(userId!=null && userId!="") {
					
					expressions.add(criteriaBuilder.equal(root.get("us").get("userId"), userId));
				}
				//用于查询某个学生的追踪记录
				if(!StringUtils.isEmpty(stuId)) {
					expressions.add(criteriaBuilder.equal(root.get("stu").get("stuid"), stuId));
				}
				return predicate;
			}
		};
	}

	@Override
	public String DelNetfollow(Integer did) {
		try {
		    netfollowsRepository.deleteById(did);
			return "删除成功";
		} catch (Exception e) {
			return "发生了错误请稍后再试";
			// TODO: handle exception
		}
	}

	
	@Override
	public String UpdNetFollow(Netfollows netf) {
		
		try {
			
	    Netfollows nes = netfollowsRepository.findById(netf.getId()).get();
	    nes.setContent(netf.getContent());
	    nes.setFollowType(netf.getFollowType());
	    nes.setFollowState(netf.getFollowState());
	    nes.setNextFollowTime(netf.getNextFollowTime());
		    netfollowsRepository.saveAndFlush(nes);
		    
			return "修改成功";
		} catch (Exception e) {
			return "发生了错误请稍后再试";
			// TODO: handle exception
		}
	}

	@Override
	public String AddNetFollow(Netfollows netf, String stuid,String userId) {
		try {
			netf.setFollowState("跟踪中");
			
			Student stu = studentrepostory.findById(stuid).get();
			
			netf.setStudentName(stu.getStuName());
			
			netf.setStu(stu);
			
			netf.setUs(userrepostory.findById(userId).get());
			
			netf.setCreateTime(sdf.format(new Date()));
			
			netf.setFollowTime(sdf.format(new Date()));
			
			    netfollowsRepository.saveAndFlush(netf);
			    
				return "添加成功";
			} catch (Exception e) {
				return "发生了错误请稍后再试";
				// TODO: handle exception
			}
	}

	@Override
	public List<Student> findAllStu() {
		// TODO Auto-generated method stub
		return studentrepostory.findAll();
	}

	

}
